package com.miracle.moa.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miracle.common.Result;
import com.miracle.common.StatusCode;
import com.miracle.moa.manager.entity.Dept;
import com.miracle.moa.manager.mapper.DeptMapper;
import com.miracle.moa.manager.service.IDeptService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author miracle
 * @since 2021-03-22
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {

    @Override
    public Result<List<Dept>> listDeptTree(String deptName) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(deptName)) {
            /* 根据部门名称模糊查询 */
            queryWrapper.lambda().like(Dept::getDeptName, deptName);
        }
        List<Dept> deptList = formatTree(super.list(queryWrapper));
        return new Result<>(StatusCode.OK, "查询成功", deptList);
    }

    /**
     * 将行数据转为树形结构
     * @param datalist 数据列表
     * @return List<com.miracle.moa.manager.entity.Dept>
     */
    private List<Dept> formatTree(List<Dept> datalist) {

        Iterator<Dept> iterator = datalist.iterator();
        List<Dept> top = new ArrayList<>();
        while (iterator.hasNext()) {
            Dept s = iterator.next();
            s.setTypeName(StringUtils.equals("01", s.getDeptType()) ? "部门" : "公司");
            boolean getParent = false;
            for (Dept p : datalist) {
                if (p.getId().equals(s.getParentId())) {
                    List<Dept> sunList = p.getChildren();
                    if (sunList == null) {
                        p.setChildren(new ArrayList<>());
                    }
                    List<Dept> children = p.getChildren();
                    children.add(s);
                    /* 排序 */
                    children.sort(Comparator.comparing(Dept::getOrderNum));
                    getParent = true;
                    break;
                }
            }
            if (!getParent) {
                top.add(s);
            }
        }
        return top;
    }
}
